<template>
  <view>
    <view>
      <button @tap="chooseImg">上传图片</button>
      <image :src="img" />
    </view>
    <view>
      <button @tap="chooseVideo">上传视频</button>
      <video :src="video" />
    </view>
  </view>
</template>

<script>
import AliOSS from '@/utils/oss/oss';
import uniRequest from "@/utils/request";

export default {
  name: "vue2",
  data() {
    return {
      client: null,
      img: '',
      video: '',
    }
  },
  onLoad(){
    this.initOss();
  },
  methods: {
    // 初始化OSS
    async initOss() {
      const resp = await uniRequest.get('获取sts接口');
      this.client = new AliOSS({
        accessKeyId: resp.data.accessKeyId,
        accessKeySecret: resp.data.accessKeySecret,
        securityToken: resp.data.securityToken,
        expiration: resp.data.expiration
      });
    },
    chooseImg(){
      uni.chooseImage({
        count: 1,
        success: async (file) => {
          const {success, data} = await this.client.value.ossUpload(file.tempFiles[0].path, file.tempFiles[0].name, 'img/')
          if (success) {
            this.img = data
          } else {
            uni.showToast({icon: 'none', title: data})
          }
        }
      })
    },
    chooseVideo(){
      uni.chooseVideo({
        count: 1,
        success: async (file) => {
          const {success, data} = await this.client.value.ossUpload(file.tempFilePath, file.name, 'video/')
          if (success) {
            this.video = data
          } else {
            uni.showToast({icon: 'none', title: data})
          }
        }
      })
    }
  }
}
</script>